package com.li.controller;

import com.li.exception.MyException;
import com.li.result.Result;
import com.li.service.SysUserService;
import com.li.system.SysUser;
import com.li.utils.JwtHelper;
import com.li.utils.MD5;
import com.li.vo.LoginVo;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: lyh
 * @Date: 2022/10/29
 * @Time: 15:10
 * @Description:
 */
@Api("用户登录接口")
@RestController
@RequestMapping("/admin/system/index")
public class IndexController {
    @Autowired
    private SysUserService sysUserService;

    //login
    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo) {
        //根据username查询数据
        SysUser sysUser = sysUserService.selectByUserName(loginVo.getUsername());
        //如果查询为空,抛异常
        if (sysUser == null){
            throw new MyException(20001,"用户不存在");
        }
        //判断密码是否一致
        if (!sysUser.getPassword().equals(MD5.encrypt(loginVo.getPassword()))){
            throw new MyException(20001,"密码错误");
        }
        //判断用户是否可用
        if (sysUser.getStatus().intValue() == 0 ){
            throw new MyException(20001,"用户已禁用");
        }
        //根据userId和username生成token字符串，通过map返回
        String token = JwtHelper.createToken(sysUser.getId(), sysUser.getUsername());

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        return Result.ok(map);
    }

    //info
    @GetMapping("/info")
    public Result getInfo(HttpServletRequest request) {
        //获取请求头token字符串
        String token = request.getHeader("token");
        //从token字符串获取用户名称（id）
        String username = JwtHelper.getUsername(token);
        //根据用户名称获取用户信息（基本信息、菜单权限、按钮权限数据）
        Map<String, Object> map = sysUserService.getUserInfo(username);

        return Result.ok(map);
    }

    //logout
    @PostMapping("/logout")
    public Result logout() {
        return Result.ok();
    }

}
